/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

(function ($) {
    var dayName = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var monthName = [ "JAN" , "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ];
    // function for date picker
    $.fn.datepick = function () {
        $this = this[0];                
        
        this.each(function (index, $this) {
            
            $this.title = $($this).find("b").html();
            $this.dateValue = $($this).find("i").html();
            var increases = $($this).find("u");
            console.log( $($this).find("u"));
            $this.increaseValue = 0;            
            for (var i = 0; i < increases.length; i++) {
                $this.increaseValue += parseInt(increases[i].innerHTML);
            }
            console.log($this.increaseValue);
            
            $($this).html("");
                        
            if ($this.title !== 'undefined') {
                $this.titleDiv = $("<div class='picker-title'>" + $this.title + "</div>").appendTo($this);
            }
            
            if (!$($this).hasClass("disabled")) {                
                $($this).click(displayDatePicker);
            }
            
            $this.dayDiv = $("<div class='day'>Mon</div>").appendTo(this);
            $this.dateDiv = $("<div class='date'>01</div>").appendTo(this);
            $this.monthDiv = $("<div class='month'>JAN</div>").appendTo(this);
            $this.yearDiv = $("<div class='year'>2014</div>");   
            
            if (!$($this).hasClass("hideYear")) {
                $this.yearDiv.appendTo(this);
            }
            
            $this.inputDiv = $("<input class='dateinput' value='' />").appendTo(this);

            // function
            $this.setDate = setDate;
            $this.updateCarret = updateCarret;
            $this.hidePicker = hidePicker;
            $this.cellSelected = cellSelected;
            
            // Init
            $this.date = new Date($this.dateValue);
            
            // increase date
            while ($this.increaseValue) {
                // increase the date
                $this.date = new Date($this.date.getFullYear(), $this.date.getMonth(), $this.date.getDate() + 1);
                // check holidate
                if (!isHoliday($this.date)){
                    $this.increaseValue--;
                }
            }
            
            if (isNaN($this.date)) {
                $this.date = new Date();
            }

            $this.setDate($this.date);                   

            // for key input
            $this.carretPosition = 0;       
        });
        
    };
    
    function isHoliday(date) {
        var isHoliday = false;
        if (date.getDay() == 0 || date.getDay() == 6) {
            isHoliday = true;
        }
        return isHoliday;
    }
    
    function setDate(date, triggerOnChanged) {        
        this.date = date;
        this.value = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00:00";
        this.dayDiv.html(dayName[date.getDay()]);
        this.dateDiv.html(date.getDate());
        this.monthDiv.html(monthName[date.getMonth()]);
        this.yearDiv.html(date.getFullYear());
        
        if (this.picker) {
            var firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
            var lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
            var i = 0;
            var j = firstDate.getDay();
            this.itemArea.find(".cell").html("&nbsp;").removeClass("selected");
            for (var d = 1; d <= lastDate.getDate(); d++) {
                var cell = this.itemArea.find(".cell" + i + "" + j).html(d);
                if (d === date.getDate()) {
                    cell.addClass("selected");
                }
                
                cell[0].picker = this;
                cell.click(cellSelected);
                
                j++;
                if (j > 6) {
                    j = 0;
                    i ++;
                }                                
            }
            
            this.monthDisplay.html(monthName[date.getMonth()] + ", " + date.getFullYear());
            
        }
        
        if (triggerOnChanged) {
            $(this).change();
        }
    }
    
    function nextMonthClick() {
        var oldDate = this.picker.date;
        var selectedDate = oldDate.getDate();
        
        var lastDateNextMonth = new Date(oldDate.getFullYear(), oldDate.getMonth() + 2, 0);
        if (selectedDate > lastDateNextMonth.getDate()) {
            selectedDate = lastDateNextMonth.getDate();
        }
        var date = new Date(oldDate.getFullYear(), oldDate.getMonth() + 1, selectedDate);
        this.picker.setDate(date, true);
    }
    
    function previousMonthClick() {
        var oldDate = this.picker.date;
        var selectedDate = oldDate.getDate();
        
        var lastDateLastMonth = new Date(oldDate.getFullYear(), oldDate.getMonth(), 0);
        if (selectedDate > lastDateLastMonth.getDate()) {
            selectedDate = lastDateLastMonth.getDate();
        }
        var date = new Date(oldDate.getFullYear(), oldDate.getMonth() - 1, selectedDate);
        this.picker.setDate(date, true);
    }

    function displayDatePicker() {
        if (!this.isDisplayed) {
            this.modalLayer = $("<div class='modal-layer'>&nbsp;</div>")
                                    .appendTo(document.body);
            this.modalLayer[0].picker = this;
            this.modalLayer.click(function(){
                this.picker.hidePicker();
            });
            
            var picker = $("<div class='picker'>"
                               + "<div class='picker-header'>"
                               +    "<a class='previous-month'>&lt;</a>" 
                               +    "<div class='month-div'>JAN</div>"
                               +    "<a class='next-month'>&gt;</a>" 
                               + "</div>" 
                               + "<div class='itemArea'></div>"
                            + "</div>");
            this.itemArea = picker.find(".itemArea");

            this.nextButton = picker.find(".next-month")[0];
            this.previousButton = picker.find(".previous-month")[0];
            this.monthDisplay = picker.find(".month-div");
            this.previousButton.picker = this;
            this.nextButton.picker = this;
            this.picker = picker;

            $(this.nextButton).click(nextMonthClick);
            $(this.previousButton).click(previousMonthClick);

            var html = "";

            // date
            for (var i = 0; i < 6; i++) {
                html += "<div class='row row" + i + "'>";
                for (var j = 0; j < 7; j++) {
                    html += "<a class='cell cell" + i + "" + j + " col" + j + "'>&nbsp;</a>";
                }
                html += "</div>";
            }

            this.itemArea.html(html);

            picker.appendTo(document.body);        
            var position = $(this).offset();
            picker.css({'top' : position.top + this.offsetHeight + 2, 'left' : position.left });                


            //
            $(this).addClass("active");

            this.setDate(this.date);

            this.inputDiv.focus();
            this.inputDiv.keypress(keyPress);
            this.updateCarret();
            this.isDisplayed = true;
        } else {
            this.hidePicker();
        }
    }
    
    function hidePicker() {
        $(this).removeClass("active");
        $(this.picker).detach();
        this.picker = false;
        this.isDisplayed = false;
        $(this).find(".focus").removeClass("focus");
        this.modalLayer.detach();
        this.modalLayer = false;
    }
    
    function cellSelected() {
        var d = parseInt(this.innerHTML);
        if (!isNaN(d)) {
            var date = new Date(this.picker.date.getFullYear(), this.picker.date.getMonth(), d);
            this.picker.setDate(date, true);
            this.picker.hidePicker();
        }
    }
    
    function keyPress(event) {
        console.log(event);        
    }
    
    function updateCarret() {
        switch (this.carretPosition / 2) {
            case 0:
                this.dateDiv.addClass("focus");
                break;
            case 1:
                this.monthDiv.addClass("focus");
                break;
            default:
                this.yearDiv.addClass("focus");
                break;
        }
    }
    
}( jQuery ));
